//
//  TableViewController.m
//  ATNetworks
//
//  Created by Ranjit2 on 16/05/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "TableViewController.h"
#import "Music.h"

@implementation TableViewController

@synthesize results;

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}



- (void)viewDidLoad {
    [super viewDidLoad];

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.results count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSString *CellIdentifier = [NSString stringWithFormat:@"Cell %@",indexPath];
    
    NSString *PlaceholderCellIdentifier = [NSString stringWithFormat:@"PlaceholderCell %@",indexPath];    
	
    // add a placeholder cell while waiting on table data
    int nodeCount = [self.results count];
	
	
	if (nodeCount == 0 && indexPath.row == 0)
    {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                           reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		
        cell.detailTextLabel.text = @"Loading…";
        
        return cell;
    }
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                       reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
	
    // Leave cells empty if there's no data yet
    if (nodeCount > 0)
    {
        // Set up the cell...
        Music *music = [self.results objectAtIndex:indexPath.row];
        
		cell.textLabel.text = music.name;
        cell.detailTextLabel.text = music.artist;
        
		// Only load cached images; defer new downloads until scrolling ends
        if (!music.image)
        {
            if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
            {
                [self startIconDownload:music forIndexPath:indexPath];
            }
            // if a download is deferred or in progress, return a placeholder image
                         
        }
        else
        {
			cell.imageView.image = music.image;
        }
		
    }
    
    
    // Set up the cell...
	
    return cell;
}

#pragma mark Table cell image support

- (void)startIconDownload:(Music *)music forIndexPath:(NSIndexPath *)indexPath
{
    ATIconDownloader *iconDownloader = [[[ATIconDownloader alloc] init] autorelease];
	iconDownloader.imageUrl = music.imageUrl;
	NSLog(@"startIconDownload iconDownloader.imageUrl is %@",iconDownloader.imageUrl);
	NSLog(@"startIconDownload indexPath is %@",indexPath);
	iconDownloader.id_ = indexPath;
	[iconDownloader openConnection:music.imageUrl withCallBackTarget:indexPath withDelegate:self];
	
	
}

-(void) imageDownloadFinish:(UIImage*)image_ withId:(NSIndexPath*)id_{
	NSLog(@"imageDownloadFinish id_ is %@",id_);
	 Music *music = [self.results objectAtIndex:id_.row];
	NSLog(@"imageDownloadFinish music.imageUrl is %@",music.imageUrl);
	[music setImage:image_];
	[self.results replaceObjectAtIndex:id_.row withObject:music];
//	[[[self.tableView cellForRowAtIndexPath:id_] imageView] setImage:image_];
	
	UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:id_];
	
	// Display the newly loaded image
	cell.imageView.image = image_;
	[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:id_] withRowAnimation:UITableViewRowAnimationNone];
	
}



// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
    if ([self.results count] > 0)
    {
        NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths)
        {
            Music *music = [self.results objectAtIndex:indexPath.row];
            
            if (!music.image) // avoid the app icon download if the app already has an icon
            {
                [self startIconDownload:music forIndexPath:indexPath];
            }
        }
    }
}


// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
    {
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


- (void)dealloc {
    [super dealloc];
}


@end

